﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace XQ.Common
{
    /// <summary>
    /// 百度IP地址查询
    /// </summary>
    public class SelectIP
    {

        public SelectIP()
        { }

        /// <summary>
        /// 读取指定IP地址的城市
        /// </summary>
        /// <param name="ip"></param>
        public string GetCity(string ip)
        {

            WebRequest Wrq = WebRequest.Create("http://www.baidu.com/s?wd=" + ip + "&rsv_bp=0&rsv_spt=3&rsv_n=2&inputT=11484");

            WebResponse Wrs = Wrq.GetResponse();

            Stream strm = Wrs.GetResponseStream();

            StreamReader sr = new StreamReader(strm, System.Text.Encoding.GetEncoding("UTF-8"));

            string allstrm;

            allstrm = sr.ReadToEnd();

            string matchs = "<p class=\"op_ip_detail\">来&nbsp;&nbsp;&nbsp;自:&nbsp;<strong>(?<location>[^<>]+?)</strong></p>";

            Match match = Regex.Match(allstrm, matchs);

            return  match.Groups["location"].Value.Split(' ')[0].Trim();

        }

        /// <summary>
        /// 获取当前IP城市
        /// </summary>
        /// <returns></returns>
        public string GetIpCity()
        {
            try
            {

                //StatInfo model = new StatInfo();

                //string ip = "58.17.209.42";

                //string ip = "";
                //if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) // using proxy
                //{
                //    ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.
                //}
                //else// not using proxy or can't get the Client IP
                //{
                //    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
                //}

                //if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
                //{
                //    ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
                //}
                //if (string.IsNullOrEmpty(ip))
                //{
                //    ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
                //}

                string ip = GetIP();
                return getIpAddr(ip);
                //return GetCity(ip);
            }
            catch(Exception e)
            {
                return e.ToString();
            }
        }

        /// <summary>
        /// 获取IP
        /// </summary>
        /// <returns></returns>
        public string GetIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                return "127.0.0.1";
            }
            return result;
        }

        /// <summary>
        /// 获取当前访问域名
        /// </summary>
        /// <returns></returns>
        public string GetUrlName()
        {
            try
            {
                string name = "";
                name = HttpContext.Current.Request.Url.Host.ToString().ToLower();

                return name;
            }

            catch
            {
                return "";
            }
        }


        #region
        //获取IP或域名地址函数  
        public String getIpAddr(String ip)
        {
            if (ip.StartsWith("http://"))
                ip = ip.Replace("http://", "");
            String IP = "http://www.ip138.com/ips1388.asp?ip=";
            IP += ip;
            IP += "&action=2";
            String ipAddr = "";

            //获取网页源码  
            System.Net.WebClient webClient = new System.Net.WebClient();
            String strSource = "";
            try
            {
                strSource = webClient.DownloadString(IP);
                //this.txbAddr.Text = strSource;  
            }
            catch (System.Net.WebException e)
            {
                return ipAddr = e.ToString();
            }

            //提取地址  
            String regex = @"<li>.+<li>";
            ipAddr = System.Text.RegularExpressions.Regex.Match(strSource, regex).ToString();
            ipAddr = ipAddr.Replace("<li>本站主数据：", "");
            ipAddr = ipAddr.Replace("</li><li>", "");
            return ipAddr;
        }  
        #endregion
    }
}
